{% extends 'sales/base.html' %}
{% load static %}
{% block breadcrumb %}
{% block extralinks %}
<style>
  .form-group label {
    font-weight: 800;
    color: black;
  }
</style>
{% endblock %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'invoices:invoices_list' %}">Invoices</a></li>
    <li class="breadcrumb-item active">{% if invoice_obj %}Edit{% else %}Create{% endif %}</li>
  </ol>
</nav>
{% endblock %}
{% block content %}
<div class="crm_invoice" style="">
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <div class="crm_form">
          <div class="row">
            <div class="col-md-9 p-5 m-auto" style=" background: #fff!important;">
              <h1 class="text-center pb-3">{% if invoice_obj %}Edit{% else %}Create{% endif %} Invoice</h1>
              <form id="formid" action='' method="POST" novalidate>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group row">
                      <label for="staticEmail" class="col-sm-4 col-form-label">Invoice
                        Title{% if form.invoice_title.field.required %}<span class="error_marker" style="color:red">
                          *</span>{% endif %} </label>
                      <div class="col-sm-8 pl-0">
                        
                        {{ form.invoice_title }}
                        <span class="error" id="id__invoice_title">{{ form.invoice_title.errors }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group row">
                      <label for="staticEmail"
                        class="col-sm-4 col-form-label">Status{% if form.status.field.required %}<span
                          class="error_marker" style="color:red">*</span>{% endif %}</label>
                      <div class="col-sm-8 pl-0">
                        
                        {{ form.status }}
                        <span class="error" id="id__status">{{ form.status.errors }}</span>
                        
                      </div>
                    </div>
                  </div>

                  <div class="col-md-12" style="margin: 0; padding: 0;">

                    <div class="form-group row" style="padding:0; margin:0;">
                      <label for="inputPassword" class="col-sm-3 col-form-label" style="">Invoice
                        Number{% if form.invoice_number.field.required %}<span class="error_marker" style="color:red">
                          *</span>{% endif %}</label>
                      <div class="col-sm-9 pl-0">
                        
                        {{ form.invoice_number }}
                        <span class="error" id="id__invoice_number">{{ form.invoice_number.errors }}</span>
                      </div>
                    </div>
                  </div>

                  
                  
                  
                  
                  <div class="col-md-12">
                    <div class="row">
                      <div class="form-group mt-5 col-md-6">
                        
                        <div class="form-group">
                          <label for="exampleInputEmail1">From Address</label>
                          {{ from_address_form.address_line }}
                          <span class="error" id="id__address_line">{{ from_address_form.address_line.errors }}</span>
                        </div>
                        {{ from_address_form.street }}
                        <span class="error" id="id__street">{{ from_address_form.street.errors }}</span>
                        <div class="row" style="margin-top: 10px;">
                          <div class="col-md-4">
                            {{ from_address_form.city }}
                            {{ from_address_form.city.errors }}
                            <span class="error" id="id__city">{{ to_address_form.city.errors }}</span>
                          </div>
                          <div class="col-md-4">
                            {{ from_address_form.state }}
                            <span class="error" id="id__state">{{ from_address_form.state.errors }}</span>
                          </div>
                          <div class="col-md-4">
                            {{ from_address_form.postcode }}
                            <span class="error" id="id__postcode">{{ from_address_form.postcode.errors }}</span>
                          </div>
                          <div class="col-md-12" style="margin-top: 10px;">
                            {{ from_address_form.country }}
                            <span class="error" id="id__country">{{ from_address_form.country.errors }}</span>
                          </div>
                        </div>
                        <br>
                      </div>
                      <div class="form-group mt-5 col-md-6">
                        
                        <div class="form-group">
                          <label for="exampleInputEmail1">To Address</label>
                          {{ to_address_form.address_line }}
                          <span class="error" id="id__address_line_">{{ to_address_form.address_line.errors }}</span>
                        </div>
                        {{ to_address_form.street }}
                        <span class="error" id="id__street_">{{ to_address_form.street.errors }}</span>
                        <div class="row" style="margin-top: 10px;">
                          <div class="col-md-4">
                            {{ to_address_form.city }}
                            {{ to_address_form.city.errors }}
                            <span class="error" id="id__city_">{{ to_address_form.city.errors }}</span>
                          </div>
                          <div class="col-md-4">
                            {{ to_address_form.state }}
                            <span class="error" id="id__state_">{{ to_address_form.state.errors }}</span>
                          </div>
                          <div class="col-md-4">
                            {{ to_address_form.postcode }}
                            <span class="error" id="id__postcode_">{{ to_address_form.postcode.errors }}</span>
                          </div>
                          <div class="col-md-12" style="margin-top: 10px;">
                            {{ to_address_form.country }}
                            <span class="error" id="id__country_">{{ to_address_form.country.errors }}</span>
                          </div>
                        </div>
                        <br>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-6 mt-5">
                    <div class="form-group row">
                      <label for="staticEmail" class="col-sm-4 col-form-label">Name
                        {% if form.name.field.required %}<span class="error_marker" style="color:red"> *
                        </span>{% endif %}</label>
                      <div class="col-sm-8 pl-0">
                        
                        {{ form.name }}
                        <span class="error" id="id__name">{{ form.name.errors }}</span>
                      </div>
                    </div>
                    <div class="form-group row">
                      <label for="staticEmail" class="col-sm-4 col-form-label">Email
                        {% if form.email.field.required %}<span class="error_marker" style="color:red"> *
                        </span>{% endif %}</label>
                      <div class="col-sm-8 pl-0">
                        
                        {{ form.email }}
                        <span class="error" id="id__email">{{ form.email.errors }}</span>
                      </div>
                    </div>
                    <div class="form-group row">
                      <label for="staticEmail"
                        class="col-sm-4 col-form-label">Phone{% if form.phone.field.required %}<span
                          class="error_marker" style="color:red"> * </span>{% endif %}</label>
                      <div class="col-sm-8 pl-0">
                        {{ form.phone }}
                        <span class="error" id="id__phone">{{ form.phone.errors }}</span>
                        
                      </div>
                    </div>
                    <div class="form-group row">
                      <label for="staticEmail" class="col-sm-4 col-form-label">Due Date
                        {% if form.due_date.field.required %}<span class="error_marker"
                          style="color:red">*</span>{% endif %}</label>
                      <div class="col-sm-8 pl-0">
                        <div id="datepicker1" class='input-group date'>
                          {{ form.due_date }}
                          <span class="input-group-addon">
                            <span class="glyphicon glyphicon-calendar"></span>
                          </span>
                        </div>
                        <span class="error" id="id__due_date">{{ form.due_date.errors }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-6 mt-5">
                    <div class="form-group row">
                      <label for="inputState" class="col-sm-4">Currency{% if form.currency.field.required %}<span
                          class="error_marker" style="color:red"> * </span>{% endif %}</label>
                      <div class="col-sm-8 pl-0">
                        {{ form.currency }}
                        <span class="error" id="id__currency">{{ form.currency.errors }}</span>
                      </div>
                    </div>
                    {% if request.user.is_superuser or request.user.role == 'ADMIN' %}
                    <div class="form-group row">
                      <label for="staticEmail" class="col-sm-4 col-form-label">Teams</label>
                      <div class="col-sm-8 pl-0">
                        
                        <select name="teams" id="id_teams" class="assigned_users form-control" multiple>
                          {% for team in teams %}
                          <option data-users="{{team.get_users}}" value="{{team.id}}"
                            {% if team in invoice_obj.teams.all %} selected="" {% endif %}>
                            {{team}}</option>
                          {% endfor %}
                        </select>
                        <span class="error" id="id__teams">{{ form.teams.errors }}</span>
                      </div>
                    </div>


                    <div class="form-group row">
                      <label class="col-sm-4 col-form-label"><span class="">Users</span></label>
                      <div class="col-sm-8 pl-0">
                        <select name="" aria-readonly="true" id="_id_assigned_to" class=" form-control" multiple>
                          {% if invoice_obj and invoice_obj.teams.all %}
                          {% for user in users %}
                          {% if user in invoice_obj.get_team_users %}
                          <option value="{{user.id}}" selected="">{{user.email}}</option>
                          {% else %}
                          <option value="{{user.id}}">{{user.email}}</option>
                          {% endif %}
                          {% endfor %}
                          {% else %}
                          {% for user in users %}
                          <option value="{{user.id}}">{{user.email}}</option>
                          {% endfor %}
                          {% endif %}
                        </select>
                      </div>
                    </div>


                    {% endif %}
                    <div class="form-group row">
                      <label for="staticEmail" class="col-sm-4 col-form-label">Assign To</label>
                      
                        
                        
                      <select class="assigned_users form-control" name="assigned_to" multiple="multiple"
                    id="id_assigned_to">
                    {% for user in users %}
                    <option value="{{user.id}}" {% if user in invoice_obj.get_assigned_users_not_in_teams or user.id in assignedto_list %}
                      selected="" {% endif %}>{{user.email}}</option>
                    {% endfor %}
                  </select>
                  <span class="error error_message" id="error_id_assigned_to">{{ form.assigned_to.errors }}</span>
                    </div>
                    <div class="form-group row">
                      <label for="staticEmail" class="col-sm-4 col-form-label">Accounts</label>
                      <div class="col-sm-8 pl-0">
                        
                        {{form.accounts}}
                        <span class="error" id="id__accounts">{{ form.accounts.errors }}</span>
                      </div>
                    </div>
                    <input type="hidden" name="from_account" value="{{request.GET.view_account}}">
                  </div>
                  <div class="col-md-12 mt-5">
                    <div class="row pt-0 pb-4">
                      <div class="form-group col-md-4">
                        <label for="inputCity">Quality Hours{% if form.quantity.field.required %}<span
                            class="error_marker" style="color:red"> * </span>{% endif %}</label>
                        
                        {{ form.quantity }}
                        <span class="error" id="id__quantity">{{ form.quantity.errors }}</span>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="inputState">Rate {% if form.rate.field.required %}<span class="error_marker"
                            style="color:red">*</span>{% endif %}</label>
                        {{ form.rate }}
                        <span class="error" id="id__rate">{{ form.rate.errors }}</span>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="inputZip">Total Amount{% if form.total_amount.field.required %}<span
                            class="error_marker" style="color:red"> * </span>{% endif %}</label>
                        {{ form.total_amount }}
                        <span class="error" id="id__total_amount">{{ form.total_amount.errors }}</span>
                        
                      </div>
                    </div>
                  </div>
                  <div class="col-md-12 mt-1">
                    <div class="form-group">
                      <label for="inputZip">Details</label>
                      {{form.details}}
                      <span class="error" id="id__details">{{ form.details.errors }}</span>
                    </div>
                  </div>
                </div>
                <div class="col-md-12">
                  <div class="col-md-12">
                    <div class="row marl buttons_row form_btn_row text-center">
                      <button class="btn btn-default save" type="submit">Save</button>
                      <a href="{% url 'invoices:invoices_list' %}" class="btn btn-default clear"
                        id="create_user_cancel">Cancel</a>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  {% endblock %}
  {% block js_block %}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
  <script type="text/javascript">

    // $(document).ready(function() {
    //   $('.assigned_users').select2();
    // });
    $(document).ready(function () {
      $("#id_contacts").select2();
      $("#id_assigned_to").select2();
      $('#id_currency').select2();
      $('#id_teams').select2();
      $('#_id_assigned_to').select2({ disabled: 'readonly' });
      {% if request.GET.view_account %}
      $("#id_accounts option[value=" + '{{request.GET.view_account}}' + "]").attr('selected', true);
      {% endif %}
      $('#id_accounts').select2();

      {% if invoice_obj %}
      $('#id_due_date').datetimepicker({
        'format': 'YYYY-MM-DD',
      })
      {% else %}
      var date = new Date();
      var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      $('#id_due_date').datetimepicker({
        'format': 'YYYY-MM-DD',
        minDate: today
      })
      {% endif %}


      $('#id_quantity').keyup(calculate);
      $('#id_rate').keyup(calculate);
      function calculate(e) {
        $('#id_total_amount').val($('#id_quantity').val() * $('#id_rate').val());
      }

    });

    $('form#formid').ajaxForm({
      type: 'POST',
      dataType: 'json',
      url: ".",
      data: $('#formid').serialize(),
      success: function (data) {
        if (data.error) {
          $('.error').html('')
          for (var key in data.errors) {
            $('#id__' + key).html("<p>" + data.errors[key][0] + "</p>");
          };
          for (var key in data.from_address_errors) {
            $('#id__' + key).html("<p>" + data.from_address_errors[key][0] + "</p>");
          };
          for (var key in data.to_address_errors) {
            $('#id__' + key + '_').html("<p>" + data.to_address_errors[key][0] + "</p>");
            console.log($('#id__' + key + '_'))
          };
          $('#submit_btn').removeAttr('disabled')
        }
        else {
          window.location = data.success_url;
        }
      }
    });

  function find_dict(dict, id){
    var index = dict.map(function(o) { return o.team; }).indexOf(parseInt(id));
    return dict[index]['users']
  }

  $("#id_teams").change(function (e) {
    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'invoices:get_teams_and_users' %}", function(data){
      // console.log(data)
          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        $('#id_assigned_to').select2().trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          // console.log("s_users", selected_users)
          var un_select_users = [].concat.apply([], selected_users)
          // console.log('un select users', un_select_users);


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
            // console.log(' selected', $(this).attr('data-users').split(','))
            // console.log('selected', $(this).attr('data-users'))
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
            // console.log('un selected', $(this).attr('data-users').split(','))
          }
        });
        // console.log('selected users teams data', users)
        var existingUsers = $('#id_assigned_to').val();
        var allUsers = users
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });

  $(document).ready(function($) {

    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'invoices:get_teams_and_users' %}", function(data){

          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        // $('#id_assigned_to').select2().val([]).trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          var un_select_users = [].concat.apply([], selected_users)


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            // $(this).attr('disabled', 'disabled')
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
          }
        });
        var existingUsers = $('#id_assigned_to').val();
        // var allUsers = users.concat(existingUsers)
        var allUsers = users
        // console.log(existingUsers)
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });
</script>
{% endblock js_block %}